<?php

namespace catchAdmin\miniapp\controller;

use uctoo\job\UploadCloudDb;
use uctoo\job\UploadCloudFunction;
use catchAdmin\wechatopen\model\AdminApplet;
use catchAdmin\wechatopen\model\Applet;
use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\miniapp\model\WechatMiniappVersion as wechatMiniappVersionModel;
use EasyWeChat\OpenPlatform\Application;
use think\facade\Filesystem;
use think\facade\Queue;
use think\helper\Str;
use uctoo\ThinkEasyWeChat\MiniProgram\CloudEnv\ServiceProvider;

class WechatMiniappVersion extends CatchController
{
    protected $wechatMiniappVersionModel;
    
    public function __construct(WechatMiniappVersionModel $wechatMiniappVersionModel)
    {
        $this->wechatMiniappVersionModel = $wechatMiniappVersionModel;
    }

    /**
     * 引入微信控制器的traits
     */
    use \uctoo\library\traits\Wechatopen;
    
    /**
     * 列表
     * @time 2021年03月24日 17:58
     * @param Request $request 
     */
    public function index(Request $request) : \think\Response
    {
        return CatchResponse::paginate($this->wechatMiniappVersionModel->getList());
    }
    
    /**
     * 保存信息
     * @time 2021年03月24日 17:58
     * @param Request $request 
     */
    public function save(Request $request) : \think\Response
    {
        return CatchResponse::success($this->wechatMiniappVersionModel->storeBy($request->post()));
    }
    
    /**
     * 读取
     * @time 2021年03月24日 17:58
     * @param $id 
     */
    public function read($id) : \think\Response
    {
        return CatchResponse::success($this->wechatMiniappVersionModel->findBy($id));
    }
    
    /**
     * 更新
     * @time 2021年03月24日 17:58
     * @param Request $request 
     * @param $id
     */
    public function update(Request $request, $id) : \think\Response
    {
        return CatchResponse::success($this->wechatMiniappVersionModel->updateBy($id, $request->post()));
    }
    
    /**
     * 删除
     * @time 2021年03月24日 17:58
     * @param $id
     */
    public function delete($id) : \think\Response
    {
        return CatchResponse::success($this->wechatMiniappVersionModel->deleteBy($id));
    }

    /**
     * 上传小程序模板
     * @param Request $request
     * @param Application $app   微信第三方平台实例
     * @param $id
     */
    public function templateCommit(Request $request,Application $app,$id) : \think\Response
    {       //查询管理员当前选中的applet
        $adminApplet = AdminApplet::where('creator_id','=',$request->user()->id)->find();
        //查询applet
        $applet = Applet::where('appid','=',$adminApplet['appid'])->find();
        //查询小程序版本
        $template = $this->wechatMiniappVersionModel->findBy($id);
        if($applet){
            $miniapp = $app->miniProgram($applet['appid'], $applet['authorizer_refresh_token']);
            $ext_json = json_decode($template['ext_json']);
            $res = $miniapp->code->commit($template['template_id'], $template['ext_json'], $template['user_version'], $template['user_desc']);

           /* $this->wxResult($res, false, function () use ($applet, $template,$ext_json) {  //TODO:上传模板成功后处理云服务端资源
                // 添加数据集合
                $dbQueueData = [
                    'applet' => $applet,
                    'cloud_dbs' => $ext_json['cloud_dbs']
                ];
                Queue::push(UploadCloudDb::class, $dbQueueData, 'uploadCloudDbQueue');
                // 上传云函数
                $funcQueueData = [
                    'applet' => $applet,
                    'cloud_functions' => $ext_json['cloud_functions']
                ];
                Queue::push(UploadCloudFunction::class, $funcQueueData, 'uploadCloudFunctionQueue');

                $this->getExperienceQrCode();
            });*/
            return CatchResponse::success($res,'上传模板成功');
        }else{
            return CatchResponse::fail('请管理员先选中要操作的小程序');
        }
    }

    /**
     * 预览小程序模板
     * @param Request $request
     * @param Application $app   微信第三方平台实例
     * @param $id
     */
    public function templatePreview(Request $request,Application $app,$id) : \think\Response
    {      //查询管理员当前选中的applet
        $adminApplet = AdminApplet::where('creator_id','=',$request->user()->id)->find();
        //查询applet
        $applet = Applet::where('appid','=',$adminApplet['appid'])->find();
        //查询小程序版本
        $template = $this->wechatMiniappVersionModel->findBy($id);
        if($applet){
            $miniapp = $app->miniProgram($applet['appid'], $applet['authorizer_refresh_token']);
            $res = $miniapp->code->getQrCode();
            $res->getBody()->rewind();
            $contents = $res->getBody()->getContents();

            if (empty($contents) || '{' === $contents[0]) {
                return CatchResponse::fail('获取失败');
            }
            $fileSystem = Filesystem::disk('public');
            $path = 'qrcode' . DIRECTORY_SEPARATOR . $adminApplet['appid'] . '.jpg';
            $result = $fileSystem->put($path, $contents);
            $path = DIRECTORY_SEPARATOR .$path;  //在windows server上这样才正常，抽风...
            if ($result) {
                $url = $request->domain() . $fileSystem->getConfig()->get('url'). str_replace(DIRECTORY_SEPARATOR, '/', $path);
                return CatchResponse::success(['experience_qrcode' => $url . '?t=' . time()],'获取预览二维码成功');
            }
            return CatchResponse::fail('获取失败');
        }else{
            return CatchResponse::fail('请管理员先选中要操作的小程序');
        }
    }

    /**
     * 提交审核
     * @param Request $request
     * @param Application $app   微信第三方平台实例
     * @param $id
     */
    public function templateAudit(Request $request,Application $app,$id) : \think\Response
    {      //查询管理员当前选中的applet
        $adminApplet = AdminApplet::where('creator_id','=',$request->user()->id)->find();
        //查询applet
        $applet = Applet::where('appid','=',$adminApplet['appid'])->find();
        //查询小程序版本
        $template = $this->wechatMiniappVersionModel->findBy($id);
        if($applet){
            $miniapp = $app->miniProgram($applet['appid'], $applet['authorizer_refresh_token']);
            $res = $miniapp->code->submitAudit([], null, null);
            $updateData = ['auditid' => $res['auditid']];
            $this->wxResult($res, 'submit_audit', function ($data) use ($id,$updateData) {
                // 保存auditid
                return CatchResponse::success($this->wechatMiniappVersionModel->updateBy($id, $updateData));
            });
        }else{
            return CatchResponse::fail('请管理员先选中要操作的小程序');
        }
    }

    /**
     * 发布小程序
     * @param Request $request
     * @param $id
     */
    public function templateRelease(Request $request,Application $app,$id) : \think\Response
    {       //查询管理员当前选中的applet
        $adminApplet = AdminApplet::where('creator_id','=',$request->user()->id)->find();
        //查询applet
        $applet = Applet::where('appid','=',$adminApplet['appid'])->find();
        //查询小程序版本
        $template = $this->wechatMiniappVersionModel->findBy($id);
        if($applet){
            $miniapp = $app->miniProgram($applet['appid'], $applet['authorizer_refresh_token']);
            $res = $miniapp->code->release();
            return CatchResponse::success($res,'小程序发布成功');
        }else{
            return CatchResponse::fail('请管理员先选中要操作的小程序');
        }
    }

    /**
     * 配置小程序模板
     * @param Request $request
     * @param $id
     */
    public function templateConfig(Request $request,Application $app,$id) : \think\Response
    {       //查询管理员当前选中的applet
        $adminApplet = AdminApplet::where('creator_id','=',$request->user()->id)->find();
        //查询applet
        $applet = Applet::where('appid','=',$adminApplet['appid'])->find();
        //查询小程序版本
        $template = $this->wechatMiniappVersionModel->findBy($id);
        if($applet){
            $miniapp = $app->miniProgram($applet['appid'], $applet['authorizer_refresh_token']);
            $ext_json = json_decode($template['ext_json']); //TODO:通过小程序模板装修模块生成ext_json

        }else{
            return CatchResponse::fail('请管理员先选中要操作的小程序');
        }
    }
}